﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using Microsoft.Office.Interop.Word;
using CommunitySystemModel;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;

namespace CommunitySystem.BO.WordExport
{
    public class WordExportBO
    {
        private Microsoft.Office.Interop.Word.Application _word = null;
        private object miss = Type.Missing;

        #region CommonAction

        /// <summary>
        /// 设置页眉
        /// </summary>
        /// <param name="word"></param>
        /// <param name="Content"></param>
        public void SetPageHeader(Microsoft.Office.Interop.Word.Application word, string Content)
        {
            word.ActiveWindow.View.Type = WdViewType.wdOutlineView;
            word.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
            word.ActiveWindow.ActivePane.Selection.InsertAfter(Content);
            word.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; // 设置右对齐 
            word.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;
        }

        /// <summary>
        /// 设置页脚
        /// </summary>
        /// <param name="word"></param>
        /// <param name="Content"></param>
        public void SetPageFooter(Microsoft.Office.Interop.Word.Application word, string Content, string FontName, int FontSize)
        {
            word.ActiveWindow.View.Type = WdViewType.wdOutlineView;
            word.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryFooter;
            word.ActiveWindow.ActivePane.Selection.InsertAfter(Content);
            word.ActiveWindow.ActivePane.Selection.Font.Name = FontName;
            word.ActiveWindow.ActivePane.Selection.Font.Size = FontSize;
            word.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; // 设置右对齐 
            word.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;
        }

        /// <summary>
        /// 换行, 将光标下移指定行数
        /// </summary>
        /// <param name="word"></param>
        /// <param name="LineCount"></param>
        public void MoveLine(Microsoft.Office.Interop.Word.Application word, int LineCount)
        {
            object count = LineCount;
            object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine; // 换一行; 
            word.Selection.MoveDown(ref  WdLine, ref  count, ref  miss); // 移动焦点 
            WdLine = Microsoft.Office.Interop.Word.WdUnits.wdCharacter;
            count = 0;
            word.Selection.MoveLeft(WdLine, count);
        }

        /// <summary>
        /// 向右移动制定位置
        /// </summary>
        /// <param name="word"></param>
        /// <param name="ColumnCount"></param>
        public void MoveRight(Microsoft.Office.Interop.Word.Application word, int ColumnCount)
        {
            object count = ColumnCount;
            object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdCharacter;
            word.Selection.MoveRight(ref  WdLine, ref  count, ref  miss); // 移动焦点 
        }

        /// <summary>
        /// 向左移动制定位置
        /// </summary>
        /// <param name="word"></param>
        /// <param name="ColumnCount"></param>
        public void MoveLeft(Microsoft.Office.Interop.Word.Application word, int ColumnCount)
        {
            object count = ColumnCount;
            object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdCharacter;
            word.Selection.MoveLeft(ref  WdLine, ref  count, ref  miss); // 移动焦点 
        }

        public void MoveEndUntil(Microsoft.Office.Interop.Word.Application word, string cset)
        {
            object Cset = cset;
            word.Selection.MoveEndUntil(ref Cset, miss);
        }



        /// <summary>

        /// 定位到指定行

        /// </summary>

        /// <param name=”lineNum”>行号</param>

        public void gotoAbsolutLine(int lineNum, Selection selection)
        {
            object dummy = System.Reflection.Missing.Value;

            object what = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToLine;

            object which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToFirst;

            object count = lineNum;

            selection.GoTo(ref what, ref which, ref count, ref dummy);

        }

        /// <summary>
        /// 删除所有word进程
        /// </summary>
        public static void KillAllWordProcess()
        {
            try
            {
                System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
                Process[] wordProcess = System.Diagnostics.Process.GetProcessesByName("winword");
                foreach (Process pro in wordProcess) //这里是找到那些没有界面的Word进程
                {
                    IntPtr ip = pro.MainWindowHandle;

                    string str = pro.MainWindowTitle; //发现程序中打开跟用户自己打开的区别就在这个属性
                    //用户打开的str 是文件的名称，程序中打开的就是空字符串
                    //if (string.IsNullOrEmpty(str))
                    //{
                    pro.Kill();
                    //}
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }

        #endregion


        /// <summary>
        /// 生成行政介绍信
        /// </summary>
        /// <param name="footer">页脚</param>
        /// <param name="_Path">模版位置，默认为空即可</param>
        /// <param name="emps">人员列表。最多5个，超出人员不写</param>
        /// <param name="From">何处来</param>
        /// <param name="To">去何处(存根)</param>
        /// <param name="DangAnCaiNiao">档案材料</param>
        /// <param name="GoZiZhuanyiZheng">工资转移</param>
        /// <param name="DeadLine">报道限期</param>
        /// <param name="dsc">备注</param>
        /// <param name="JingBan">经办人</param>
        /// <param name="riqi">日期</param>
        /// <param name="DaoDanwei">到***单位</param>
        /// <param name="DiaoDongYuanying">调动原因</param>
        /// <returns>返回字符串为下载字符串</returns>
        public string GerneratorXingZhenJieshaoXing(string footer, string _Path, ObservableCollection<PersonnelInfoModelForWord> emps,
            string From, string To, string DangAnCaiNiao, string GoZiZhuanyiZheng, DateTime DeadLine, string dsc, string JingBan,
            DateTime riqi, string DaoDanwei, string DiaoDongYuanying)
        {
            KillAllWordProcess();
            _word = new Microsoft.Office.Interop.Word.Application();
            _word.Visible = true;//设置Word应用程序为不可见
            var miss = Type.Missing;
            string uploadFolder = System.Web.Hosting.HostingEnvironment.MapPath("~/wordTemplete");
            object path = uploadFolder + @"\" + @"行政介绍信模版.doc";// @"行政介绍信模版.doc";
            if (!string.IsNullOrEmpty(_Path))
                path = _Path;

            var doc = _word.Documents.Open(ref path, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss,
                ref miss, ref miss);
            string NameList = "";
            //设置页脚
            this.SetPageFooter(_word, footer, "仿宋", 15);
            this.MoveLine(_word, 3);
            for (int i = 0; i < emps.Count && i < 5; i++)
            {
                _word.ActiveWindow.ActivePane.Selection.InsertAfter(emps[i].Name);
                NameList += emps[i].Name + ",";
                this.MoveRight(_word, 2);
                _word.ActiveWindow.ActivePane.Selection.InsertAfter(emps[i].Political);
                this.MoveRight(_word, 2);
                _word.ActiveWindow.ActivePane.Selection.InsertAfter(emps[i].OriginalPosition);
                this.MoveRight(_word, 2);
                this.MoveLine(_word, 1);
                this.MoveLeft(_word, 2);
            }
            if (5 - emps.Count > 0)
            {
                this.MoveLine(_word, 5 - emps.Count);
            }

            NameList = NameList.TrimEnd(',');
            if (emps.Count < 5)
            {
                this.MoveEndUntil(_word, "来");
                this.MoveRight(_word, 3);
            }
            else
            {
                this.MoveRight(_word, 2);
            }
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(From);//何处来
            this.MoveLine(_word, 1);
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(To);//去何处
            this.MoveLine(_word, 1);
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(DangAnCaiNiao);//档案材料
            this.MoveLine(_word, 1);
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(DangAnCaiNiao);//工资转移证
            //this.MoveLine(_word, 1);
            this.MoveRight(_word, 4);
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(DeadLine.Year + "");//限期
            this.MoveRight(_word, 2);
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(DeadLine.Month + "");//限期
            this.MoveRight(_word, 3);
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(DeadLine.Day + "");//限期
            this.MoveLine(_word, 1);
            //this.MoveRight(_word, 4);
            if (!string.IsNullOrEmpty(dsc))
            {
                _word.ActiveWindow.ActivePane.Selection.InsertAfter(dsc);//备注
                this.MoveRight(_word, 1);
            }
            
                //this.MoveLine(_word, 1);
                this.MoveRight(_word, 6);
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(JingBan);//经办人

            this.MoveRight(_word, 3);
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(DeadLine.Year + "");//日期
            this.MoveRight(_word, 2);
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(DeadLine.Month + "");//日期
            this.MoveRight(_word, 2);
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(DeadLine.Day + "");//日期

            this.MoveRight(_word, 4);
            this.MoveLine(_word, 2);
            this.MoveRight(_word, 5);
            object count = NameList.Length + 6;
            _word.ActiveWindow.ActivePane.Selection.Delete(ref miss, ref count);
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(NameList);

            string mun = string.Empty;
            switch (emps.Count)
            {
                case 1:
                    mun = "壹";
                    break;
                case 2:
                    mun = "贰";
                    break;
                case 3:
                    mun = "叁";
                    break;
                case 4:
                    mun = "肆";
                    break;
                case 5:
                    mun = "伍";
                    break;
            }
            count = 31 - (int)count;
            this.MoveRight(_word, (int)count);
            count = 1;
            _word.ActiveWindow.ActivePane.Selection.Delete(ref miss, ref count);
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(mun);
            this.MoveRight(_word, 8);
            count = DaoDanwei.Length + 6;
            _word.ActiveWindow.ActivePane.Selection.Delete(ref miss, ref count);
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(DaoDanwei);
            this.MoveLine(_word, 4);
            this.MoveEndUntil(_word, "年");
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(riqi.Year + "");
            this.MoveEndUntil(_word, "月");
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(riqi.Month + "");
            this.MoveEndUntil(_word, "日");
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(riqi.Day + "");
            this.MoveRight(_word, 3);
            this.MoveLine(_word, 1);
            for (int i = 0; i < emps.Count && i < 5; i++)
            {


                _word.ActiveWindow.ActivePane.Selection.InsertAfter(emps[i].Name);
                this.MoveRight(_word, 2);
                _word.ActiveWindow.ActivePane.Selection.InsertAfter(emps[i].Gender);
                this.MoveRight(_word, 2);
                _word.ActiveWindow.ActivePane.Selection.InsertAfter(emps[i].Political);
                this.MoveRight(_word, 2);
                _word.ActiveWindow.ActivePane.Selection.InsertAfter(emps[i].OriginalOrg);
                this.MoveRight(_word, 2);
                _word.ActiveWindow.ActivePane.Selection.InsertAfter(emps[i].OriginalPosition);

                this.MoveRight(_word, 2);
                if (!string.IsNullOrEmpty(emps[i].Level))
                {
                    _word.ActiveWindow.ActivePane.Selection.InsertAfter(emps[i].Level);
                    this.MoveRight(_word, 1);
                }
                this.MoveRight(_word, 1);
                if (i == 0 && !string.IsNullOrEmpty(dsc))
                {
                    _word.ActiveWindow.ActivePane.Selection.InsertAfter(dsc);
                    this.MoveRight(_word, 1);
                }
                this.MoveRight(_word, 2);
            }
            if (5 - emps.Count > 0)
            {
                this.MoveLine(_word, 5 - emps.Count);
            }
            this.MoveEndUntil(_word, "记");
            this.MoveRight(_word, 4);
            this.MoveLine(_word, 1);
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(DiaoDongYuanying);
            this.MoveRight(_word, 2);
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(DangAnCaiNiao);
            this.MoveRight(_word, 2);
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(GoZiZhuanyiZheng);
            this.MoveRight(_word, 3);
            this.MoveEndUntil(_word, "年");
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(DeadLine.Year + "");
            this.MoveEndUntil(_word, "月");
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(DeadLine.Month + "");
            this.MoveEndUntil(_word, "日");
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(DeadLine.Day + "");

            string saveFolder = System.Web.Hosting.HostingEnvironment.MapPath("~/cash");
            object savepath = saveFolder + @"\" + @"行政介绍信.doc";// @"行政介绍信模版.doc";
            if (File.Exists(savepath.ToString()))
                File.Delete(savepath.ToString());
            doc.SaveAs(ref savepath, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss);
            
            doc.Close(miss, miss, miss);
            
            _word.Quit();
            KillAllWordProcess();
            return "/cash/行政介绍信.doc";
        }

        /// <summary>
        /// 获取所有的行政介绍信
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ObservableCollection<Word_XingZhengJieShaoLetter> GetXingZhengJieshaoXing(string condition)
        {
            ObservableCollection<Word_XingZhengJieShaoLetter> letters = new ObservableCollection<Word_XingZhengJieShaoLetter>();
            StringBuilder sql = new StringBuilder("select * from Word_XingZhengJieShaoLetter");
            if (!string.IsNullOrEmpty(condition))
            {
                sql.Append("  where  ");
                sql.Append(condition);
            }
            DataSet ds = AccessHelper.GetInstance().ExcuteDataSet(sql.ToString());
            if (ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    letters.Add(AccessHelper.FillDataRowToEntity<Word_XingZhengJieShaoLetter>(ds.Tables[0], dr));
                }
            }
            return letters;
        }

        public string InsertWord_XingZhengJieShaoLetter(Word_XingZhengJieShaoLetter entity)
        {
            string filePath = null;
            try
            {
                #region 生成word
                if (entity.Status == "开出")
                {
                    string footer = string.Format("沪徐  {0}  字第  {1}  号                                            沪徐  {0}  字第  {1}  号", entity.Year, entity.NO);
                    string _path = "";
                    ObservableCollection<PersonnelInfoModelForWord> emps = new ObservableCollection<PersonnelInfoModelForWord>();
                    #region 人员信息
                    if (!string.IsNullOrEmpty(entity.emp1Name))//第一个人
                    {
                        emps.Add(new PersonnelInfoModelForWord()
                        {
                             Name = entity.emp1Name,
                             Gender = entity.emp1Gender,
                             Level = entity.emp1Level,
                             OriginalOrg = entity.emp1OrginalDepartment,
                             OriginalPosition = entity.emp1OriginalPosition,
                             Political = entity.emp1Political,
                        });
                    }
                    if (!string.IsNullOrEmpty(entity.emp2Name))//第2个人
                    {
                        emps.Add(new PersonnelInfoModelForWord()
                        {
                            Name = entity.emp2Name,
                            Gender = entity.emp2Gender,
                            Level = entity.emp2Level,
                            OriginalOrg = entity.emp2OrginalDepartment,
                            OriginalPosition = entity.emp2OriginalPosition,
                            Political = entity.emp2Political,
                        });
                    }
                    if (!string.IsNullOrEmpty(entity.emp3Name))//第3个人
                    {
                        emps.Add(new PersonnelInfoModelForWord()
                        {
                            Name = entity.emp3Name,
                            Gender = entity.emp3Gender,
                            Level = entity.emp3Level,
                            OriginalOrg = entity.emp3OrginalDepartment,
                            OriginalPosition = entity.emp3OriginalPosition,
                            Political = entity.emp3Political,
                        });
                    }
                    if (!string.IsNullOrEmpty(entity.emp4Name))
                    {
                        emps.Add(new PersonnelInfoModelForWord()
                        {
                            Name = entity.emp4Name,
                            Gender = entity.emp4Gender,
                            Level = entity.emp4Level,
                            OriginalOrg = entity.emp4OrginalDepartment,
                            OriginalPosition = entity.emp4OriginalPosition,
                            Political = entity.emp4Political,
                        });
                    }
                    if (!string.IsNullOrEmpty(entity.emp5Name))
                    {
                        emps.Add(new PersonnelInfoModelForWord()
                        {
                            Name = entity.emp5Name,
                            Gender = entity.emp5Gender,
                            Level = entity.emp5Level,
                            OriginalOrg = entity.emp5OrginalDepartment,
                            OriginalPosition = entity.emp5OriginalPosition,
                            Political = entity.emp5Political,
                        });
                    }
                    #endregion
                    try
                    {
                        filePath = GerneratorXingZhenJieshaoXing(footer, _path, emps, entity.From, entity.To, entity.DangAnCainiao, entity.SalaryTransferLicence, (DateTime)entity.DeadLine, entity.DSC,
                             entity.JingBanRen, (DateTime)entity.CreateDate, entity.To, entity.TransferReason);
                    }
                    catch (Exception ex)
                    {
                        return ex.Message;
                    }
                   //if (File.Exists(filePath))
                   //{
                   //    var fs = File.OpenRead(filePath);
                   //    _word = new byte[fs.Length];
                   //    fs.Read(_word, 0, (int)fs.Length);
                   //    //File.Delete(filePath);
                   //}
                }
                #endregion
                if (entity.ID > 0)
                {
                    UpdateWord_XingZhengJieShaoLetter(entity);
                    string sql = "update Word_InterviewTemplete set IsActive = 0 where id != " + entity.ID;
                    AccessHelper.GetInstance().ExecuteNonQuery(sql);

                }
                else
                {
                    List<SqlParameter> parameters = null;
                    string sql = AccessHelper.GeneratorInsertSQL(entity, new string[1] { "ZiHao" }, "ID", "", out parameters);
                    AccessHelper.GetInstance().ExecuteSql(sql, parameters.ToArray());
                    sql = "update Word_InterviewTemplete set IsActive = 0 where id != (select top 1 id from Word_InterviewTemplete order by id desc)";
                    AccessHelper.GetInstance().ExecuteNonQuery(sql);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return filePath;
        }

        private bool UpdateWord_XingZhengJieShaoLetter(Word_XingZhengJieShaoLetter entity)
        {
            List<SqlParameter> parameters = null;
            string sql = AccessHelper.GeneratorUpdateSQL(entity, new string[1] { "ZiHao" }, "ID", "", out parameters);
            AccessHelper.GetInstance().ExecuteSql(sql, parameters.ToArray());
            return true;
        }

        public bool DeleteWord_XingZhengJieShaoLetter(int id)
        {
            try
            {
                string sql = "delete Word_XingZhengJieShaoLetter where ID=" + id;
                AccessHelper.GetInstance().ExecuteSql(sql, null);
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 获得当前年的最大字号
        /// </summary>
        /// <param name="Year"></param>
        /// <returns></returns>
        public int GetNOAcoordingToYear(int Year)
        {
            string sql = "select top 1 NO from Word_XingZhengJieShaoLetter where Year = " + Year + " order by NO desc";
            DataSet ds = AccessHelper.GetInstance().ExcuteDataSet(sql);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return (int)ds.Tables[0].Rows[0][0];
            }
            else
            {
                return 0;
            }
        }
    }
}
